<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :destroyOnClose="true"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="父级节点" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-tree-select ref="treeSelect"
                         :placeholder="'请选择父级节点'"
                         v-decorator="[''+pidField]"
                         :dict="currentTableName+','+textField+',id,'+'id='+model[pidField]"
                         :pidField="pidField"
                         pidValue="0"
                         :hasChildField="hasChildrenField">
          </j-tree-select>
        </a-form-item>
        <template  v-for="(po,index) in columns">
          <a-form-item :label="po.dbFieldTxt" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date v-if="po.fieldShowType =='date'" :placeholder="'请选择'+po.dbFieldTxt" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :trigger-change="true" style="width: 100%"/>
            <j-date v-else-if="po.fieldShowType =='datetime'" :placeholder="'请选择'+po.dbFieldTxt" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :trigger-change="true" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>

            <j-popup v-else-if="po.fieldShowType =='popup'"
              v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]"
              :trigger-change="true"
              :org-fields="po.dictField"
              :dest-fields="po.dbFieldName"
              :code="po.dictTable"
              :field="po.dbFieldName"
              @callback="popupCallback"/>
            <j-search-select-tag v-else-if="po.fieldShowType =='sel_search'" :placeholder="'请选择'+po.dbFieldTxt" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :dict="po.dictTable+','+po.dictText+','+po.dictField+','+po.condition"/>
            <j-category-select v-else-if="po.fieldShowType =='cat_tree'" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :pcode="po.oldDictTable"/>
            <j-select-depart v-else-if="po.fieldShowType =='sel_depart'" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :trigger-change="true"/>
            <j-select-user-by-dep v-else-if="po.fieldShowType =='sel_user'" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :trigger-change="true"/>
            <a-textarea v-else-if="po.fieldShowType =='textarea'" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" rows="4" :placeholder="'请输入'+po.dbFieldTxt"/>
            <j-dict-select-tag v-else-if="po.fieldShowType=='list' || po.fieldShowType=='radio'" :type="po.fieldShowType" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]"  :trigger-change="true" :dictCode="po.dictTable+','+po.dictText+','+po.dictField+','+po.condition" :placeholder="'请选择'+po.dbFieldTxt"/>
            <j-multi-select-tag v-else-if="po.fieldShowType=='list_multi' || po.fieldShowType=='checkbox'"  :type="po.fieldShowType" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :trigger-change="true" :dictCode="po.dictTable+','+po.dictText+','+po.dictField+','+po.condition" :placeholder="'请选择'+po.dbFieldTxt"/>
            <a-input-number v-else-if="po.fieldShowType=='int' || po.fieldShowType=='double' || po.fieldShowType=='BigDecimal'" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :placeholder="'请输入'+po.dbFieldTxt" style="width: 100%"/>
            <j-upload v-else-if="po.fieldShowType=='file'" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :trigger-change="true"></j-upload>
            <j-image-upload isMultiple v-else-if="po.fieldShowType=='image'" v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" ></j-image-upload>
            <a-input v-else  v-decorator="[''+po.dbFieldName, validatorRules[po.dbFieldName]]" :placeholder="'请输入'+po.dbFieldTxt"></a-input>
          </a-form-item>

        </template>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction,getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JDate from '@/components/jeecg/JDate'
import JUpload from '@/components/jeecg/JUpload'
import JImageUpload from '@/components/jeecg/JImageUpload'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
import JTreeSelect from '@/components/jeecg/JTreeSelect'
import JPopup from '@comp/jeecg/JPopup'
export default {
  name: 'OufuformTreeModal',
  components: {
    JDate,
    JUpload,
    JImageUpload,
    JSelectDepart,
    JSelectUserByDep,
    JDictSelectTag,
    JMultiSelectTag,
    JTreeSelect,
    JPopup,
    JSearchSelectTag
  },
  props: {
    code: ''
  },
  data() {
    return {
      form: this.$form.createForm(this),
      title: '操作',
      width: 800,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      validatorRules: {},
      url: {
        getColumns: '/online/cgform/autoGetFormItem',
        add: '/online/cgform/api/public/autoAddForm',
        edit: '/online/cgform/api/public/autoAddForm',
      },
      expandedRowKeys: [],
      pidField: '',

      currentTableName:'',
      hasChildrenField:'',
      textField:'',
      columns:[],
    }
  },
  created() {

  },
  methods: {
    add(obj) {
      this.edit(obj)
    },
    async edit(record) {
      await getAction(`${this.url.getColumns}`,{autoHeadId:this.code}).then(res => {
        if(res.success){
          this.currentTableName = res.result.head.tableName
          this.pidField = res.result.head.treeParentIdField
          this.hasChildrenField = res.result.head.treeIdField
          this.textField = res.result.head.treeFieldname

          let formColums = res.result.schema.properties
          let arr = []
          for (let i in formColums) {
            if (formColums[i].view != 'tab') {
              formColums[i].columName = i
              arr.push(formColums[i])
            }
          }
          let currColumns = this.sortByKey(arr, 'order')
          let textFieldIndex = -1
          for(let a=0;a<currColumns.length;a++){

            let po = currColumns[a];
            //处理验证
            if(po.dbFieldName != 'id'){
              let rules = [];
              if(po.fieldMustInput ==1 || po.fieldValidType =='*'){
                rules.push({ required: true, message: '请输入'+po.dbFieldTxt})
              }else if(po.fieldValidType=='only'){
                rules.push({ validator: (rule, value, callback) => validateDuplicateValue(this.currentTableName, po.dbFieldName, value, this.model.id, callback)})
              }else if(po.fieldValidType=='n6-16'){
                rules.push({ pattern: /\d{6,16}/, message: '请输入6到16位数字!'})
              }else if(po.fieldValidType=='*6-16'){
                rules.push({ pattern: /^.{6,16}$/, message: '请输入6到16位任意字符!'})
              }else if(po.fieldValidType=='s6-18'){
                rules.push({ pattern: /^.{6,18}$/, message: '请输入6到18位任意字符!'})
              }else if(po.fieldValidType=='url'){
                rules.push({ pattern: /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/, message: '请输入正确的网址!'})
              }else if(po.fieldValidType=='e'){
                rules.push({ pattern: /^([\w]+\.*)([\w]+)@[\w]+\.\w{3}(\.\w{2}|)$/, message: '请输入正确的电子邮件!'})
              }else if(po.fieldValidType=='m'){
                rules.push({ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!'})
              }else if(po.fieldValidType=='p'){
                rules.push({ pattern: /^[1-9]\d{5}$/, message: '请输入正确的邮政编码!'})
              }else if(po.fieldValidType=='s'){
                rules.push({ pattern: /^[A-Z|a-z]+$/, message: '请输入字母!'})
              }else if(po.fieldValidType=='n'){
                rules.push({ pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'})
              }else if(po.fieldValidType=='z'){
                rules.push({ pattern: /^-?\d+$/, message: '请输入整数!'})
              }else if(po.fieldValidType=='money'){
                rules.push({ pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的金额!'})
              }
              this.validatorRules[po.dbFieldName] = {rules:rules};
            }
          }

          if(textFieldIndex!=-1){
            let textFieldColumn = currColumns.splice(textFieldIndex,1)
            currColumns.unshift(textFieldColumn[0])
          }
          this.columns = [...currColumns]
        }
      })
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(
            pick(this.model, this.pidField, this.hasChildrenField)
        )
        this.columns.forEach(item =>{
          this.form.setFieldsValue(
            pick(this.model,item.dbFieldName),
          )
        })
      })
    },
    sortByKey(array, key) {
      return array.sort(function (a, b) {
        var x = a[key]
        var y = b[key]
        return x < y ? -1 : x > y ? 1 : 0
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let old_pid = this.model[this.pidField]
          let formData = Object.assign(this.model, values)
          let new_pid = this.model[this.pidField]
          formData['autoHeadId'] = this.code;
          if(formData['children']){
            delete formData['children']
          }
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.submitSuccess(formData, old_pid == new_pid)
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    popupCallback(row) {
      for(var key in row){
        this.model[key] = row[key]
        let fieldval = pick(this.model, key)
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
      }
    },
    submitSuccess(formData, flag) {
      if (!formData.id) {
        let treeData = this.$refs.treeSelect.getCurrTreeData()
        this.expandedRowKeys = []
        this.getExpandKeysByPid(formData[this.pidField], treeData, treeData)
        this.$emit('ok', formData, this.expandedRowKeys.reverse())
      } else {
        this.$emit('ok', formData, flag)
      }
    },
    getExpandKeysByPid(pid, arr, all) {
      if (pid && arr && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].key == pid) {
            this.expandedRowKeys.push(arr[i].key)
            this.getExpandKeysByPid(arr[i]['parentId'], all, all)
          } else {
            this.getExpandKeysByPid(pid, arr[i].children, all)
          }
        }
      }
    },
  },
}
</script>